package com.xthh._function._socket;

import android.os.Handler;


import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;

public class HH_OkHttpmanager {
    //_________________________定义成员变量____________________________
    private static HH_OkHttpmanager okHttpmanager;
    private static Handler mhandler;
    private static OkHttpClient mcliengt;



    //__________________________使用构造方法完成初始化___________________
    private HH_OkHttpmanager(){
        /*mcliengt = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
        mhandler = new Handler();*/

        mcliengt = new OkHttpClient.Builder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                 .sslSocketFactory(HH_SSLSocketClient.getSSLSocketFactory())//配置
                .hostnameVerifier(HH_SSLSocketClient.getHostnameVerifier())//配置
                .build();
        mhandler = new Handler();
    }

//__________________________使用单例模式报漏一个方法，给外部使用___________

    public static HH_OkHttpmanager getInsetance(){
        if (okHttpmanager==null){
            okHttpmanager=new HH_OkHttpmanager();
        }
        return okHttpmanager;
    }
//________________定义接口______________________


    public interface Func1{
        void onResponse(String rsult);
    }
    public interface Func2{
        void onResponse(byte[] result);
    }
    public interface Func3{
        void onResponse(String jsonObject);
    }
    //处理网络请求的方法返回的是字符串
    public static void onsuccessjsonstring(final String jsonVaule,final Func1 callBack){

        mhandler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack!=null) {
                    callBack.onResponse(jsonVaule);
                }
            }
        });

    }
    //请求返回字符串
    public static void asynTaskJson(String url, final Func1 callBack){
        Request request = new Request.Builder().url(url).build();
        mcliengt.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                onsuccessjsonstring(response.body().string(),callBack);
            }
        });

    }




    //请求返回图片
    private static void onSuccessJsonStringMethod(final byte[] jsonValue,final Func2 callBack){
        mhandler.post(new Runnable() {
            @Override
            public void run() {
                if(callBack!=null){
                    callBack.onResponse(jsonValue);
                }
            }
        });
    }

    /**
     * 同步请求数据 在android 开发中不常用，因为阻塞UI线程
     *
     * @param url
     * @return
     */
    public String syncGitByURL(String url) {
        Request request = new Request.Builder().url(url).build();
        //构建一个request请求
        Response response = null;
        try {
            //同步请求数据
            response = mcliengt.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public void asyncJsonStringByURL(final String url,final Func2 callBack){
        final Request request = new Request.Builder().url(url).build();
        mcliengt.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                onSuccessJsonStringMethod(response.body().bytes(),callBack);
            }
        });
    }

    //请求返回Map集合
    private void onSuccessMap(final String jsonValue, final Map<String , String > parms, final Func3 callBack){
        mhandler.post(new Runnable() {
            @Override
            public void run() {
                if(callBack!=null){
                    callBack.onResponse(jsonValue);
                }
            }
        });
    }

    public void asyncJsonStringMap(final String url, final Map<String,String> map, final Func3 callBack){
        FormBody.Builder builder = new FormBody.Builder();
        if (map!=null&&!map.isEmpty()){
            for (Map.Entry<String,String> entry:map.entrySet()) {
                builder.add(entry.getKey(),entry.getValue());
            }
        }
        FormBody build = builder.build();
        final Request request = new Request.Builder().url(url).build();
        mcliengt.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                onSuccessMap(response.body().string(),map,callBack);

            }
        });
    }

}